#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: effective_test_bugs.py
# Author: ChenChangSong
# Date: 2025-11-02

"""
功能描述: 有效bug
"""
import json

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.parent.parent))

from comm.common_code import *

def effective_bugs_info(name_value,time_value,template):
    """获取有效的bug信息。
    有效：同意拒绝|已拒绝（不予受理）|已确认未复现|拒绝(内部bug)|拒绝（线上：重复/非问题）
    name_value:姓名
    time_value:时间
    template:内部模板 或 线上模板
    """
    excel_data = get_excel_data()
    url = "https://www.tapd.cn/api/search_filter/search_filter/search"

    # 构建search_data的JSON结构
    search_data = {
        "data": [
            {
                "id": "2",
                "fieldDisplayName": "状态",
                "fieldIsSystem": "1",
                "fieldOption": "not_in",
                "fieldSystemName": "status",
                "fieldType": "select",
                "selectOption": [],
                "value": "同意拒绝|已拒绝（不予受理）|已确认未复现|拒绝(内部bug)|拒绝（线上：重复/非问题）",
                "entity": "bug"
            },
            {
                "entity": "bug",
                "fieldDisplayName": "测试人员",
                "fieldSubEntityType": "",
                "fieldIsSystem": "1",
                "fieldOption": "in",
                "fieldSystemName": "te",
                "fieldType": "user_chooser",
                "selectOption": [],
                "value": f"{name_value};",
                "id": "4"
            },
            {
                "entity": "bug",
                "fieldDisplayName": "预计结束",
                "fieldIsSystem": "1",
                "fieldOption": "in",
                "fieldSystemName": "source",
                "fieldType": "select",
                "selectOption": [],
                "value": f"{template}",
                "id": "5",
                "fieldLabel": "缺陷根源"
            },
            {
                "id": "7",
                "fieldLabel": "创建时间",
                "fieldOption": "between",
                "fieldType": "datetime",
                "fieldSystemName": "created",
                # "value": "2025-07-01 00:00,2025-09-30 23:59",
                "value": f"{time_value}",
                "fieldIsSystem": "1",
                "entity": "bug"
            }
        ],
        "optionType": "AND",
        "needInit": "1"
    }
    
    # 将search_data转换为字符串并构建payload
    payload = json.dumps({
        "workspace_ids": f"{excel_data['项目ID']}",
        "search_data": json.dumps(search_data),
        "obj_type": "bug",
        "search_type": "advanced",
        "page": 1,
        "perpage": "100",
        "block_size": 50,
        "parallel_token": "",
        "order_field": "created",
        "order_value": "desc",
        "show_fields": [],
        "extra_fields": [],
        "display_mode": "list",
        "version": "1.1.0",
        "only_gen_token": 0,
        "exclude_workspace_configs": [],
        "from_pro_dashboard": 1,
        "dsc_token": "qeSs1MkPb6GKkSam"
    })
    headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Cookie': excel_data["Cookie"],
    'Origin': 'https://www.tapd.cn',
    'Referer': 'https://www.tapd.cn/tapd_fe/worktable/search?queryToken=4e254cde728e0f89bb23ecb3152baeaa',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.562.400 QQBrowser/19.6.6725.400',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"'
    }

    response_code,response_data = api_request(method="POST", url=url, headers=headers, data=payload)

    # print(response_data)
    if response_code == 200:
        total_count = response_data["data"]["total_count"]
    else:
        total_count = 0
    logger.info(f"获取到的有效bug数量为：{total_count}")
    return int(total_count)


if __name__ == "__main__":
    effective_bugs_info(name_value='陈昌松',time_value="2025-07-01 00:00,2025-09-30 23:59",template="内部模板")
